﻿using Microsoft.Extensions.Primitives;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Http;

namespace AbpProjectTemplate.Web.Extensions
{
    public static class HttpRequestExtensions
    {
        public static string GetAbsoluteUri(this HttpContext httpContext, string url)
        {
            var request = httpContext.Request;
            return new StringBuilder()
                .Append(request.Scheme)
                .Append("://")
                .Append(request.Host)
                .Append(request.PathBase)
                .Append(url)
                .ToString();
        }

        public static string GetClientIp(this HttpContext httpContext)
        {
            var findHeaderKeys = new string[] { "X-Forwarded-For", "X-Real-IP", "PROXY_FORWARDED_FOR" };
            var request = httpContext.Request;
            foreach (var key in findHeaderKeys)
            {
                if (request.Headers.TryGetValue(key, out StringValues vals))
                    return vals.First();
            }
            return httpContext.Connection.RemoteIpAddress.ToString();
        }
    }
}
